package com.yzt.zhuju.rx;

import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import io.reactivex.Observable;
import io.reactivex.functions.Predicate;


/**
 * <pre>
 *     author : TK
 *     time   : 2017/04/22
 *     desc   : Rx工具类
 * </pre>
 */
public final class RxUtils {
    private RxUtils() {
        throw new IllegalStateException();
    }

    /**
     * 绑定生命周期
     *
     * @param lifecycle
     * @param event
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> LifecycleTransformer<T> bindLifecycle(@NonNull final Observable<R> lifecycle, @NonNull final R event) {
        return bind(takeUntilEvent(lifecycle, event));
    }

    private static <R> Observable<R> takeUntilEvent(final Observable<R> lifecycle, final R event) {
        return lifecycle.filter(new Predicate<R>() {
            @Override
            public boolean test(R lifecycleEvent) {
                return lifecycleEvent.equals(event);
            }
        });
    }


    private static <T, R> LifecycleTransformer<T> bind(@NonNull final Observable<R> lifecycle) {
        return new LifecycleTransformer<>(lifecycle);
    }

    public static boolean checkMainThread() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            Log.e("checkMainThread", "should be called on the main thread !");
            return false;
        }
        return true;
    }

}
